var jwt = require("jsonwebtoken");
var randomstring = require("randomstring");
var express = require("express");
var router = express.Router();

/**
 * type User:
 * {
 *     userId: "user id",
 *     userName: "zhangsan",
 *     nickName: "法外狂徒-张三",
 *     password: "123456",
 * }
 */
const users = [];

router.post("/register", function (req, res, next) {
    const { userName, nickName, password } = req.body;
    if (!userName.trim() || !password.trim()) {
        return res.json({ code: "1001", message: "用户名或密码不能为空" });
    }
    users.push({ userId: randomstring.generate(7), userName, nickName, password });
    return res.json({ code: "0000", message: "注册成功" });
});

router.post("/login", function (req, res, next) {
    const { userName, password } = req.body;
    if (!userName.trim() || !password.trim()) {
        return res.json({ code: "1001", message: "用户名或密码不能为空" });
    }
    const user = users.find((item) => item.userName === userName && item.password === password);
    if (!user) {
        return res.json({ code: "1002", message: "用户名或密码不正确" });
    }
    const payload = {
        userId: user.userId,
        nickName: user.nickName,
    };
    const token = jwt.sign(payload, "3d-meta", { expiresIn: "30d" });
    return res.json({ code: "0000", token });
});

router.post("/userinfo", function (req, res, next) {
    const { token } = req.body;
    try {
        const { userId } = jwt.verify(token, "3d-meta");
        const { password, ...data } = users.find((item) => item.userId === userId);

        res.json({ code: "0000", data });
    } catch (error) {
        return res.json({ code: "1003", message: "token解析失败" });
    }
});

module.exports = router;
